package com.alex.aichat.controller;

import com.alex.aichat.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/chat")
public class ChatController {

    @Autowired
    private ChatService chatService;

    @PostMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamChat(@RequestBody Map<String, Object> payload) {
        SseEmitter emitter = new SseEmitter(0L);

        List<Map<String, String>> messages = (List<Map<String, String>>) payload.get("messages");
        boolean deepthinking = Boolean.parseBoolean(payload.getOrDefault("deepthinking", "true").toString());
        // 新增：获取preset
        String preset = payload.getOrDefault("preset", "").toString().trim();

        // 只有当 preset 不为空时，插入到消息最前面 (role:user)
        if (!preset.isEmpty()) {
            Map<String, String> presetMsg = Map.of("role", "user", "content", preset);
            messages = new java.util.ArrayList<>(messages); // 避免原列表不可变
            messages.add(0, presetMsg); // 插到最前面
        }

        List<Map<String, String>> finalMessages = messages;
        new Thread(() -> {
            try {
                chatService.streamChat(finalMessages, deepthinking, (reasoning, reply) -> {
                    try {
                        if (reasoning != null && !reasoning.isEmpty()) {
                            emitter.send(SseEmitter.event()
                                    .name("reasoning")
                                    .data(reasoning));
                        }
                        if (reply != null && !reply.isEmpty()) {
                            emitter.send(SseEmitter.event()
                                    .name("reply")
                                    .data(reply));
                        }
                    } catch (Exception e) {
                        emitter.completeWithError(e);
                    }
                });
                emitter.complete();
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        }).start();
        return emitter;
    }
}